package com.android.demo_20220829.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.baselibrary.interface_.OkHttpCallBack;
import com.android.baselibrary.responce.BaseResponce;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.tool.XXPermisionUtil;
import com.android.baselibrary.view.Comm_HeadView;
import com.android.baselibrary.view.MultiStateView;
import com.android.demo_20220829.R;
import com.android.demo_20220829.adapter.A_ModelAdapter;
import com.android.demo_20220829.adapter.BlueToothListAdapter;
import com.android.demo_20220829.constants.Constants;
import com.android.demo_20220829.manager.API_Manager;
import com.android.demo_20220829.responce.BaseListData;
import com.hjq.permissions.OnPermissionCallback;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import cn.wandersnail.ble.Device;
import cn.wandersnail.ble.EasyBLE;
import cn.wandersnail.ble.callback.ScanListener;

public class Scan_ListActivity extends BaseActivity {

    @BindView(R.id.multiplestatusView)
    MultiStateView multiplestatusView;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.comm_title)
    Comm_HeadView comm_title;

    BlueToothListAdapter adapter;

    List<Device> deviceList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_onlylist;
    }

    @Override
    protected void initView() {
        comm_title.setTitle("BLE列表");
        comm_title.setLeftImgVisible(View.GONE);
        multiplestatusView.setOnRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                multiplestatusView.setViewState(MultiStateView.ViewState.LOADING);
                getData();
            }
        });

        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new BlueToothListAdapter(mContext);
        recyclerview.setAdapter(adapter);
        adapter.setData(deviceList);

        smartrefreshlayout.setEnableLoadMore(false);
        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        smartrefreshlayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }
        });
    }

    @Override
    protected void initData() {
        EasyBLE.getInstance().addScanListener(scanListener);
        List<String> permission = getNeedPermissions();
        XXPermisionUtil.requstPermision(mContext, new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                getData();
            }
        }, permission.toArray(new String[permission.size()]));
    }

    private final ScanListener scanListener = new ScanListener() {
        @Override
        public void onScanStart() {
            Log.i("test", "开始扫描");
        }

        @Override
        public void onScanStop() {
            Log.i("test", "结束扫描");
            smartrefreshlayout.finishRefresh();
        }

        @Override
        public void onScanResult(@NonNull Device device, boolean isConnectedBySys) {
            if(TextUtils.isEmpty(device.getName())) return;
            boolean has = false;
            for (int i = 0; i < deviceList.size(); i++) {
                if (deviceList.get(i).getName().equals(device.getName())) {
                    has = true;
                }
            }
            if (!has) {
                deviceList.add(device);
                adapter.notifyDataSetChanged();
                Log.i("扫描到设备：" + device.getName());
            }

        }

        @Override
        public void onScanError(int errorCode, @NotNull String errorMsg) {
            switch (errorCode) {
                case ScanListener.ERROR_LACK_LOCATION_PERMISSION://缺少定位权限
                    // ToastUtils.showShort("缺少定位权限");
                    break;
                case ScanListener.ERROR_LOCATION_SERVICE_CLOSED://位置服务未开启
                    //               ToastUtils.showShort("位置服务未开启");
                    break;
                case ScanListener.ERROR_LACK_SCAN_PERMISSION://缺少搜索权限
                    //  ToastUtils.showShort("缺少搜索权限");
                    break;
                case ScanListener.ERROR_LACK_CONNECT_PERMISSION://缺少连接权限
                    //  ToastUtils.showShort("缺少连接权限");
                    break;
                case ScanListener.ERROR_SCAN_FAILED://搜索失败
                    //   ToastUtils.showShort("搜索出错：" + errorCode);
                    break;
            }
            Log.i("errorCode:" + errorCode);
        }
    };


    //下拉刷新
    private void refreshData() {
        deviceList.clear();
        adapter.notifyDataSetChanged();
        getData();
    }

    //上拉加载
    private void loadMoreData() {
        getData();
    }

    //获取数据
    private void getData() {
        if (EasyBLE.getInstance().isInitialized()) {
            EasyBLE.getInstance().stopScan();
            EasyBLE.getInstance().stopScanQuietly();
            EasyBLE.getInstance().startScan();
        }
    }

    //需要进行检测的权限
    private List<String> getNeedPermissions() {
        List<String> list = new ArrayList<>();
        //target sdk版本在29以上的需要精确定位权限才能搜索到蓝牙设备
        if (getApplicationInfo().targetSdkVersion >= 29) {
            list.add(Manifest.permission.ACCESS_FINE_LOCATION);
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        } else {
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        //Android 12需要
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            list.add(Manifest.permission.BLUETOOTH_SCAN);
            list.add(Manifest.permission.BLUETOOTH_CONNECT);
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        return list;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EasyBLE.getInstance().isInitialized()) {
            EasyBLE.getInstance().stopScan();
        }
    }

    //点击事件
    //    @OnClick({R.id.tv_sendcode})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.tv_sendcode:
//                break;
//        }
//    }
}
